package com.youlu.campus.service.wechat.impl;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.base.exception.BusinessException;

import com.youlu.campus.entity.domain.WechatAccessToken;
import com.youlu.campus.entity.domain.WechatSubSribeDomain;
import com.youlu.campus.entity.domain.WechatSubscribeRes;
import com.youlu.campus.service.wechat.WechatH5Service;
import com.youlu.campus.service.wechat.WechatNotifyService;
import lombok.extern.slf4j.Slf4j;
import net.polyv.live.util.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Slf4j
@Service
public class WechatNotifyServiceImpl implements WechatNotifyService {
    @Autowired
    private WechatH5Service wechatH5Service;
    // 公众号AppId
    @Value("${sys.pay.wx.wxAppId}")
    protected String appId;
    // 公众号Secret
    @Value("${sys.pay.wx.wxAppSecret}")
    protected String appSecret;
    // 订阅消息发送地址
    private String wechatSubscribeUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token=%s";

    @Override
    public boolean sendSubSribe(WechatSubSribeDomain wechatSubSribeDomain) {
        log.info(":>>> 开始发送模版消息:{}", wechatSubSribeDomain);
        if (Objects.isNull(wechatSubSribeDomain)) {
            log.error(":>>> 发送模版消息参数错误");
            throw new BusinessException("发送模版消息参数错误");
        }
        try {
            WechatAccessToken wechatAccessToken = wechatH5Service.getAccessToken(appId, appSecret);

            String result = HttpClientUtil.getInstance().sendHttpPost(String.format(wechatSubscribeUrl, wechatAccessToken.getAccessToken()), new HashMap<>(), JSON.toJSONString(wechatSubSribeDomain));
            log.info(":>>> 发送模版消息:{}", result);
            if (StringUtils.isBlank(result)) {
                log.error(":>>> 发送模版消息错误");
                return false;
            }
            WechatSubscribeRes res = JSON.parseObject(result, WechatSubscribeRes.class);
            if (res.getErrcode() == 0) {
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error(":>>> 发送模版消息错误:{}", e);
            return false;
        }

    }
}
